<?php

namespace app\helper\ChannelSdk;

use app\atrait\Single;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Arr;

class XuTeng
{

    use Single;

    private string $appId;
    private string $appKey;
    private string $payKey;


    public function __construct()
    {
        $this->appId = '100174';
        $this->appKey = 'd3d716b0246d71dc860d97275c7c653b';
        $this->payKey = '3bf9078ab5d948168008d7e06feab440';
    }


    public function loginAuth($uid, $token): array
    {
        $url = 'https://game.aimiplay.com';
        $param = [
            'appid' => $this->appId,
            'username' => $uid,
            'token' => $token,
        ];
        $param['sign'] = $this->Sign($param);
        $http = new Client();
        try {
            $res = $http->request('POST', $url . '/Login/checkToken', [
                'form_params' => $param,
            ]);
            $result = json_decode($res->getBody(), true);
        } catch (GuzzleException $e) {
            return [
                'state' => false,
                'message' => $e->getMessage(),
            ];
        }

        return [
            'state'   => $result['code'] === 0,
            'message' => $result['msg'] ?? '',
            'data'    => $result['code'] === 0
                ? [
                    'uid'         => $result['data']['uid'] ?? '',
                    'username'    => $result['data']['username'] ?? '',
                    'channel_id'  => $result['data']['channel_id'] ?? '',
                    'channel_name'=> $result['data']['channel_name'] ?? '',
                ]
                : [],
        ];

    }


    /**
     * 参数签名
     *
     * @param array $param
     * @return string
     */
    public function Sign(array $param): string
    {
        // 注意：按照接口文档顺序拼接参数
        $signStr = 'appid=' . urlencode($param['appid'])
            . '&username=' . urlencode($param['username'])
            . '&token=' . urlencode($param['token'])
            . '&appkey=' . $this->appKey;

        return md5($signStr);
    }


//    /**
//     * 参数签名
//     *
//     * @param $param
//     * @return string
//     */
//    public function Sign($param): string
//    {
//
//        $signStr = Arr::query(Arr::sortRecursive($param));
//        $signStr .= '&pay_key=' . $this->payKey;
//
//        return md5($signStr);
//
//    }

}
